package com.ruoyi.api.controller;

import com.ruoyi.api.service.VimMessageService;
import com.ruoyi.api.service.VimUserApiService;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.api.entity.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author 乐天
 */
@RestController
@RequestMapping("/api/sys/messages")
public class MessageController {

    @Resource
    private VimMessageService vimMessageService;

    @Resource
    private ISysUserService iSysUserService;

    @Resource
    private VimUserApiService vimUserApiService;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private RedisCache redisCache;


//    /**
//     * 分页查询消息信息
//     * @param chatId
//     * @param fromId
//     * @param type
//     * @param pageNum
//     * @param pageSize
//     * @return
//     */
    @GetMapping
    public AjaxResult list(String chatId, String fromId, String type, Long pageNum, Long pageSize) {
        pageNum = pageNum == null ? 1 : pageNum;
        List<Message> messageVoList = vimMessageService.list(chatId, fromId, type, pageNum, pageSize);
        for (Message message : messageVoList) {
            message.setMine(fromId.equals(String.valueOf(message.getFromId())));
            SysUser sysUser = iSysUserService.selectUserById(Long.parseLong(message.getFromId()));
            message.setAvatar(sysUser.getAvatar());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("messageList", messageVoList);
        map.put("pageNo", pageNum);
        map.put("count", vimMessageService.count(chatId, fromId, type));
        map.put("pageSize", pageSize);
        redisCache.setCacheObject("count:" +  chatId + "_" + fromId, "0");
        //获取群组中的总条数
        Long zSet = redisTemplate.opsForZSet().size("message-" + chatId);
        //用户id+群组id,最这次查询的值做一个保存
        redisCache.setCacheObject("count_group:" + fromId + "_" + chatId, zSet);
        return AjaxResult.success(map);
    }

}

